package com.jxsm.cz.service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Record;
import com.jxsm.cz.biz.BizUserSign;
import com.jxsm.cz.biz.BizUserSignDetail;
import com.jxsm.cz.model.UserSign;
import com.jxsm.cz.model.UserSignDetail;
import com.jxsm.cz.util.Validate;
import com.jxsm.jfinal.core.JxDb;
import com.jxsm.jfinal.core.ServiceController;
import com.jxsm.web.aop.AuthIgnore;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author guodegen
 * @description
 * @date 2020/10/12 16:53
 */
@AuthIgnore
@ControllerBind(controllerKey = "/userSign")
public class UserSignService extends ServiceController {
    /**
     * 用户签到
     */
    public void added(){
        UserSign userSign = this.getModel(UserSign.class);
        Record signConfig = JxDb.findFirst("select initscore,timespan,scoreadd from system_sign_config");
        int initScore = signConfig.get("initscore");
        int timeSpan = signConfig.get("timespan");
        int scoreAdd = signConfig.get("scoreadd");
        long currentSign = userSign.getCount(" userid=? and FROM_UNIXTIME(signtime,'%Y-%m-%d')=curdate()",userSign.get("userid"));
        if(currentSign>0){
            this.renderJson("{\"msg\":\"您今日已签到！\",\"success\":false}");
        }else{
            UserSignDetail userSignDetail = new UserSignDetail();
            //判断是否从未进行过签到
            long userScore = userSignDetail.getCount("userid=?",userSign.get("userid"));
            int signScore = 0;
            if(userScore>0){
                userSignDetail = userSignDetail.findById(userSign.get("userid"));
                int userSignDays = Integer.parseInt(Validate.isNullToDefault(userSignDetail.get("signdays"),"0"));
                signScore = initScore + (userSignDays/timeSpan)*scoreAdd;
                //判断前一天是否签到过
                long signYesterday =  userSign.getCount(" userid=? and FROM_UNIXTIME(signtime,'%Y-%m-%d')=FROM_UNIXTIME(?-86400,'%Y-%m-%d')",userSign.get("userid"),userSign.get("signtime"));
                int today = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
                //如果昨天签到过，且今天不是1号
                if(signYesterday>0 && today!=1){
                    userSign.set("signscore",signScore);
                    userSignDetail.set("signdays",userSignDays+1);
                    int userTotalScore = Integer.parseInt(Validate.isNullToDefault(userSignDetail.get("totalscore"),"0"));
                    int userSignScore = Integer.parseInt(Validate.isNullToDefault(userSignDetail.get("signscore"),"0"));
                    userSignDetail.set("totalscore",userTotalScore + signScore);
                    userSignDetail.set("signscore",userSignScore + signScore);
                }else{
                    signScore = initScore;
                    userSign.set("signscore",initScore);
                    int userTotalScore = Integer.parseInt(Validate.isNullToDefault(userSignDetail.get("totalscore"),"0"));
                    int userSignScore = Integer.parseInt(Validate.isNullToDefault(userSignDetail.get("signscore"),"0"));
                    userSignDetail.set("totalscore",userTotalScore + initScore);
                    userSignDetail.set("signscore",userSignScore + initScore);
                    userSignDetail.set("signdays",1);
                }
                userSign.save();
                userSignDetail.update();
            }else{
                signScore = initScore;
                userSignDetail.set("userid",userSign.get("userid"));
                userSignDetail.set("totalscore", initScore);
                userSignDetail.set("signdays", 1);
                userSignDetail.set("signscore", initScore);
                userSignDetail.set("otherscore", 0);
                userSign.set("signscore",initScore);
                userSign.save();
                userSignDetail.save();
            }
            this.renderJson("{\"msg\":\"签到成功！获得"+signScore+"积分\",\"success\":true}");
        }
    }

    /**
     * 获取当月签到信息
     */
    public void getMonthSignDays(){
        //用户id
        String userId = this.getPara("userId");
        //开始时间
        String beginTime = this.getPara("beginTime");
        //结束时间
        String endTime = this.getPara("endTime");
        List<Record> userSignRecords = JxDb.find("select FROM_UNIXTIME(signtime,'%d') signday from user_sign where userid=? and signtime" +
                ">=UNIX_TIMESTAMP(?) and signtime<=UNIX_TIMESTAMP(?)",userId,beginTime,endTime);
        Map<String,Object> result = new HashMap<>();
        result.put("success",true);
        result.put("data",userSignRecords);
        this.renderJson(JSONObject.toJSONString(result));
    }

    /**
     * 获取初始用户初始签到信息
     */
    public void getInitData(){
        //用户id
        String userId = this.getPara("userId");
        //本周的最后一天
        String lastTime = this.getPara("lastTime");
        //开始时间
        String beginTime = this.getPara("beginTime");
        //结束时间
        String endTime = this.getPara("endTime");
        //获取本周的签到记录
        List<Record> userSignRecords = JxDb.find("select FROM_UNIXTIME(signtime,'%d') signday from user_sign where userid=? and signtime" +
                ">=UNIX_TIMESTAMP(?)-604800 and signtime<=UNIX_TIMESTAMP(?)",userId,lastTime,lastTime);
        //获取用户签到总分数，连续签到天数
        Record userData = JxDb.findFirst("select totalscore,signdays from user_sign_detail where userid=?",userId);
        //获取本月签到天数
        int signDays = JxDb.queryInt("select count(1) monthdays from user_sign where userid=? " +
                "and signtime>=UNIX_TIMESTAMP(?) and signtime<=UNIX_TIMESTAMP(?)",userId,beginTime,endTime);
        //判断是否连续签到
        int signSerial =  JxDb.queryInt("select count(1) yesterday from user_sign where " +
                "userid=? and (FROM_UNIXTIME(signtime,'%Y%m%d')=CURDATE()-1 or FROM_UNIXTIME(signtime,'%Y-%m-%d')=CURDATE())",userId);
        if(userData==null){
            userData = new Record();
            userData.set("totalscore",0);
            userData.set("signdays",0);
        }
        if(signSerial==0){
            userData.set("signdays",0);
        }
        userData.set("monthdays",signDays);
        Map<String,Object> result = new HashMap<>();
        result.put("success",true);
        result.put("list",userSignRecords);
        result.put("data",userData);
        this.renderJson(JSONObject.toJSONString(result));
    }
}
